/* 保存早安心语海报 */
var requestManager = require('../../../utils/requestManager.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bgImgUrl:'',
    imageWidth: 0,
    imageHeight: 0,
    qrCodeUrl:'',
    qrCodeTop: 0,
    content:'',
    canvasWidth:wx.getSystemInfoSync().windowWidth - 30,
    canvasHeight:500,
    shareImgSrc:'',
    morning_path:"",//缓存的背景图
    qrcode_path:"",//缓存的二维码图片
    show_img:false,//加载的图片先隐藏
    loaded:true
  },

  /////////////// 私有方法 ///////////////
  /**
   * 获取背景图的
   */
  getImageWidthAndHeight: function (imageUrl) {
    var that = this
    wx.getImageInfo({
      src: imageUrl,
      success: function (res) {
        console.log(res)
        var imgscale = res.width / res.height;
        let imgWidth = that.data.canvasWidth - 25 * 2;
        let imgHeight = imgWidth / imgscale;
        // 计算图片的显示尺寸
        that.setData({
          imageWidth: imgWidth,
          imageHeight: imgHeight,
        })
      }
    })  
  },
  /////////////// 网络请求 ///////////////
  requestPoster: function (shopId) {
    var that = this
    requestManager.getRequest('innermost/poster/record', {}, function (res) {
      let status = res.status
      if (status == 0) {
        // 获取图片信息
        that.getImageWidthAndHeight(res.detail['image_url'])
        // 更新UI
        that.setData({
          bgImgUrl: res.detail['image_url'],
          qrCodeUrl: res.detail['image_qrcode_url'],
          content: res.detail['saying']
        })
        wx.getImageInfo({//缓存背景
          src: res.detail['image_url'],
          success:function(storage_bg_res){
            console.log(storage_bg_res.path)
            that.setData({
              morning_path:storage_bg_res.path,
              loaded:false
            })
          }
        })
        wx.getImageInfo({//缓存二维码
          src: res.detail['image_qrcode_url'],
          success:function(storage_qrcode_res){
            that.setData({
              qrcode_path:storage_qrcode_res.path,
              loaded: false
            })
          }
        })
      }
    })
  },

  /////////////// 网络请求 ///////////////
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  //加载完图片显示
  load_show_img: function () {
    let that = this;
    let animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in',
      delay: 0
    })
    animation.opacity(1).step()
    that.setData({
      show_img: true,
      animationData: animation.export()
    })
  },

  /**
   * 绘制多行文本，由于文字比较多，这里我们写了一个函数处理
   */
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 15;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },

  /**
   * 绘制canvas
   */
  drawCanvas() {
    var that = this;
    var bgImageHeight = that.data.imageHeight;
    let bgImgTopMargin = 20;
    let lRMargin = 25;

    const context = wx.createCanvasContext('share',this)
    context.setFillStyle('#FFFFFF')
    context.fillRect(0, 0, that.data.canvasWidth, 1000)

    //先把图片放在本地
    // 布局
    context.drawImage(that.data.morning_path, lRMargin, bgImgTopMargin, that.data.imageWidth, bgImageHeight)
    let qrCodeWidth = 61;
    let qrTextHeight = 8;
    let qrText = '识别二维码关注';
    let qrMargin = 8;
    // x计算 canvas宽度 - 外边距 - 二维码距离canvas边界
    var startX = that.data.canvasWidth - lRMargin - qrMargin;

    // 二维码文字属性设置
    context.setFontSize(8)
    context.setFillStyle('#FFFFFF')
    // 计算文字的宽度
    let qrTextWidth = context.measureText(qrText).width;
    console.log('qrTextWidth宽度')
    console.log(qrTextWidth)
    // 文字与二维码图片之间的边距
    var qrToTextMargin = Math.abs(qrCodeWidth - qrTextWidth);
    console.log('文字与二维码图片之间的边距')
    console.log(qrToTextMargin / 2)
    // 文字 二维码 x
    var qrTStartX, qrStartX;
    // 文字的上边 y计算 图片距canvas的top + 图片高 - 二维码文字的高度
    let qrTStartY = bgImgTopMargin + that.data.imageHeight - (qrTextHeight + qrCodeWidth) - 10;
    // 二维码的top = 文字的y + 文字的高度
    let qrStartY = qrTStartY + qrTextHeight;
    
    if (qrTextWidth > qrCodeWidth) {
      // 如果文字宽度大于二维码宽度
      console.log('如果文字宽度大于二维码宽度')
      startX -= qrTextWidth;
      qrTStartX = startX;
      qrStartX = startX + qrToTextMargin / 2;
    } else {
      startX -= qrCodeWidth;
      qrTStartX = startX + qrToTextMargin / 2;
      qrStartX = startX;
    }
    console.log('文字 x')
    console.log(qrTStartX)
    console.log('二维码 x')
    console.log(qrStartX)

    // 绘制文字
    context.fillText(qrText, qrTStartX, qrTStartY)
  
    // 绘制二维码图片 先把图片放在本地
    context.drawImage(that.data.qrcode_path, qrStartX, qrStartY, qrCodeWidth, qrCodeWidth)
    context.setFillStyle('#5C5C56')
    context.setFontSize(10)

    let titleHeight = that.drawText(context, that.data.content, lRMargin, bgImgTopMargin + bgImageHeight + 20, 15, that.data.canvasWidth - 2 * lRMargin)
    // 更改canvas的高度
    that.setData({
      canvasHeight: bgImgTopMargin + bgImageHeight + 10 + titleHeight
    })
    // 绘画   
    context.draw()
    wx.showToast({
      title: '分享图片生成中...',
      icon: 'loading',
      duration: 1000
    });
    console.log("开始倒计时")
    setTimeout(function () {
      // 3.canvas画布转成图片
      wx.canvasToTempFilePath({
        canvasId: 'share',
        success: function (canvasToRes) {
          that.setData({
            shareImgSrc: canvasToRes.tempFilePath
          })
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                //请求授权
                wx.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success(res) {
                    //用户调用成功之后，后续再调用不会出现弹框
                    //获取图片信息
                    wx.getImageInfo({
                      src: that.data.shareImgSrc,
                      success: function (ret) {
                        var path = ret.path;
                        //保存图片
                        that.saveImageToPhotosAlbum(path)
                      }
                    })
                  },
                  fail(res) {
                    wx.showToast({
                      title: '您已拒绝授权',
                      icon: 'none'
                    })
                  }
                })
              } else {
                //获取图片信息
                wx.getImageInfo({
                  src: that.data.shareImgSrc,
                  success: function (ret) {
                    var path = ret.path;
                    that.saveImageToPhotosAlbum(path)
                  }
                })
              }
            }
          })
        },
        fail: function (res) {
          console.log(res)
        }
      }, that)
    }, 1000)  
  },

  /**
   * 保存图片到相册
   */
  saveImageToPhotosAlbum(url) {
    wx.saveImageToPhotosAlbum({
      filePath: url,
      success: function (res) {
        console.log(res);
        wx.showModal({
          title: '图片保存成功',
          content: '图片保存到相册了，去发圈噻~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3'
        })
      }
    })
  },
  /////////////// 私有方法 ///////////////

  /////////////// 事件 ///////////////
  /* 保存早安心语分享到朋友圈 */
  saveShareBtnAction: function () {
    var that = this
    // 绘制canvas
    that.drawCanvas(that)
  },
  /////////////// 事件 ///////////////

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()//隐藏转发按钮
    let shopId = app.globalData.shop
    this.requestPoster(shopId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})